var FormUtils = function () {

    var validateDefaults={
        rules: {
            ursername:{
                required: true,
                minlength: 6
            },
            password: {
                required: true,
                minlength: 6
            },
        }
    }

    setValues = function (formId, valueObj, dateFormat) {
        $(formId).find('input,select,textarea,p').each(function () {

            var name = $(this).attr('name');
            var value = Object.byString(valueObj, name),
                tag = this.tagName,
                type = this.type;
            // 如果没有值，则默认为""
            if (value == null || value == undefined) {
                value = "";
                return;
            }

            if (value.code && value.name) {
                //如果是枚举的话，value直接用code。
                value = value.code;
            }

            if (tag == "textarea") {
                // 如果为textarea则通过html赋值
                this.innerHTML = value;
                return;
            }
            if (tag == "P") {
                // 如果为textarea则通过html赋值
                $(this).text(value);
                return;
            }

            if (type == "select") {
                $(this).find('option[value="' + value + '"]').attr("selected", true);
                return;
            }

            if (type == "checkbox" || type == 'radio') {
                var $object = $('input[name="' + name + '"]').filter('[value="' + value + '"]');
                $object.prop('checked', true);
                return;
            }

            this.value = value;

        });
    };

    /**
     * 使form不可编辑
     * @param formId
     */
    disableForm = function (formId) {
        $(formId).find('input,select,textarea,button').each(function () {
            $(this).attr("disabled", true);
        });
    }
    /**
     * 枚举类的formatter
     * @param val
     * @returns {string}
     */
    enumFormatter =  function enumFormatter(val) {
        if (val) {
            return val.name;
        }
        return '';
    }

    /**
     * 可以编辑form
     * @param formId
     */
    enableForm = function (formId) {
        $(formId).find('input,select,textarea,button').each(function () {
            $(this).attr("disabled", false);
        });
    }

    /**
     * 清除form表单
     * @returns {*}
     */
    clearForm = function (formId) {
        $(formId).find('input,select,textarea,img').each(function () {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (type == 'text' || type == 'password' || tag == 'textarea' || type == "hidden")
                this.value = '';
            else if (type == 'checkbox' || type == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = !-1;
            else if (type = 'img')
                $(this).attr("src", "");
        });
    }


    /**
     * 获取表单的参数
     */
    getFormObj = function (formId) {
        var serializeObj = {};
        var $form = $(formId);
        $($form.serializeArray()).each(function () {
            if (this.value) {
                serializeObj[this.name] = this.value;
            }
        });

        //获取多选的下拉菜单的值
        $form.find('.selectpicker').each(function (i, select) {
            var val = $(select).selectpicker('val');
            if (val) {
                var name = $(select).attr('name');
                serializeObj[name] = val;
            }
        });

        return serializeObj;
    };

    /**
     * 校验
     * @param form
     * @param options
     * @param callback 通过后的回调方法
     */
    validate = function (form, options) {
        var newOp = $.extend(true,options,validateDefaults);
        $(form).validate(newOp);
    }

    /**
     *  var opt ={
                message:$dialog,
                title:'创建用户',
                formId:"form_sample_1"
            }
     FormUtils.openDialog(opt);
     * @param options
     * @returns {*}
     */
    openDialog = function (options) {
        var dlg,dialogDefaults;
        //弹出框风格的表单验证的默认设置
        dialogDefaults = {
            message: '',
            domId: '', //打开dialog的容器
            formId: '',
            loadingMsg: '',
            url: '',
            title: "请输入信息",
            success: null, //成功时候执行的方法
            error: null, //失败时候执行的方法
            closed: false,
            cache: false,
            width: 400,
            top: DLG_TOP,
            modal: true,
            animateIn: '',
            animateOut : '',
            okBtnText:"确定",
            onClickOkBtn:null,
            unCloseAfterSubmit:null,//确定之后不关闭窗口
            beforeSubmit: null, // 提交之前的事件,如果返回true,则表示可以提交表单。
            extendButtons: [],//扩展的按钮
            callback : function(result) {

            },
            buttons: {
                success: {
                    label: options.okBtnText || "确定",
                    className: "btn btn-primary",
                    callback: function() {
                        if ($.isFunction(options.onClickOkBtn)) {
                            options.onClickOkBtn();
                            if (!options.unCloseAfterSubmit) {
                                closeDialog(dlg);
                            }
                        } else {
                            //找到表单和表单提交的url
                            var $form;
                            if (options.formId) {
                                $form = dlg.find("#" + options.formId);
                            } else {
                                $form = dlg.find('form:first');
                            }
                            var url = options.url || $form.attr('action');
                            var data = FormUtils.getFormObj($form);
                            if (options.beforeSubmit && $.isFunction(options.beforeSubmit)) {
                                //如果beforeSubmit的结果是false,表示阻止提交。
                                var beforeSubmitResult = options.beforeSubmit(data);
                                if (!beforeSubmitResult) {
                                    return false;
                                }
                            }
                            //先判断是否验证成功。
                            if ($($form.selector).validate().form()) {
                                var ajaxOpt = {
                                    container: dlg,
                                    loadingMsg: options.loadingMsg,
                                    url: url,
                                    data: data,
                                    type: 'post',
                                    success: function (data) {
                                        if ($.isFunction(options.success)) {
                                            options.success(data);
                                        }
                                        if (!options.unCloseAfterSubmit) {
                                            closeDialog(dlg);
                                        }
                                    }
                                };
                                if (options.contentType) {
                                    ajaxOpt.contentType = options.contentType;
                                    if (ajaxOpt.contentType == "application/json") {
                                        ajaxOpt.data = $.toJSON(data);
                                    }
                                }
                                $.Ajax(ajaxOpt);
                            }
                        }
                        return false;
                    }
                },
                danger: {
                    label: '关闭',
                    className: 'btn-default',
                    callback: function () {

                    }
                  },
            },
        };
        options = $.extend({}, dialogDefaults, options);
        $.each(options.extendButtons, function (i, eb) {
            options.buttons.unshift(eb);
        });
        dlg = bootbox.dialog(options);
        return dlg;
    }
    
    function closeDialog($dialog) {
        $dialog.remove();
    }

    return {
        setValues:setValues,
        disableForm:disableForm,
        enableForm:enableForm,
        clearForm:clearForm,
        getFormObj:getFormObj,
        validate:validate,
        openDialog:openDialog,
        closeDialog:closeDialog,
        enumFormatter:enumFormatter
    }
}()
